#include "include/LoginDialog.h"
#include <QtSql/QSqlQuery>
#include <QMessageBox>
#include "include/client.h"


LoginDialog::LoginDialog(QWidget* parent,Client** currentClientPtr):
    QDialog(parent),
    loginButton(new QPushButton),
    registerButton(new QPushButton),
    currentClient(currentClientPtr)
{
    //初始化界面
    InitWindows();
}

LoginDialog::~LoginDialog()
{
}

void LoginDialog::onOpenLoginDialog()
{
    registerIndex->hide();
    QString name = username->text();
    QString pwd = password->text();

    if (!name.isEmpty() && !pwd.isEmpty()) {
        // 要将对象创建在堆上，若是创建在栈上有可能会被内存释放
        Client* client = new Client();
        int64_t id = client->SearchClient(name.toStdString(), pwd.toStdString());
        if (id != -1) {
            // 登录成功
            (*currentClient) = client->SearchClient(id); // 假设currentClient是类的成员变量，用来引用当前登录的用户
            QMessageBox*msgBox = new QMessageBox();
            msgBox->information(this, "信息", "登录成功！");
            this->close(); // 关闭登录窗口
            printf("当前用户Id: %lld\n", (*currentClient)->getClientId());
            // 发送登录成功信号
            emit loginSuccess();
        }
        else {
            // 登录失败
            QMessageBox::information(this, "信息", "姓名或密码错误！");
        }
    }
    else {
        // 显示对话框
        QMessageBox::information(this, "信息", "姓名或密码不能为空！");
    }
}

// 点击注册按钮后的动作
void LoginDialog::onOpenRegisterDialog()
{
    registerIndex->show();
    registerIndex->move(0, 0); // 将其移动到右侧
    QString name = username->text();
    QString pwd = password->text();
    QString ph = phone->text();

    if (name!=""&& pwd!=""&& ph!="") {
        Client* client = new Client();
        if (client->SearchClientExist(name.toStdString(), ph.toStdString())) {
            // 雪花算法注册用户Id
            Snowflake generator(1, 1);
            int64_t userId = generator.nextId();
            // 用户名和电话都没有被注册
            if(client->AddClient(userId,name.toStdString(), ph.toStdString(), pwd.toStdString())) {
                // 注册成功！
                printf("注册成功");
                QMessageBox::information(this, "信息", "注册成功！");
            }
        }
        else {
            // 被占用
            printf("被占用");
            QMessageBox::information(this, "信息", "用户名或电话已经注册！");
        }
        
    }
    else {
        // 显示对话框
        QMessageBox::information(this, "信息", "姓名、密码或电话不能为空！");
    }

}
